<template>
  <div class="app-container">

    <div class="filter-container">
      <el-input v-model="userQuery.username" placeholder="用户名" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-input v-model="userQuery.name" placeholder="姓名" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-select v-model="userQuery.gender" placeholder="请选择性别" clearable style="width: 200px" class="filter-item" @keyup.enter.native="handleFilter">
        <el-option v-for="item in genderOptions" :key="item.key" :label="item.label" :value="item.key" />
      </el-select>
      <el-input v-model="userQuery.phone" placeholder="手机号" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-select v-model="userQuery.status" placeholder="请选择状态" clearable style="width: 200px" class="filter-item" @keyup.enter.native="handleFilter">
        <el-option v-for="item in statusOptions" :key="item.key" :label="item.label" :value="item.key" />
      </el-select>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        添加
      </el-button>
      <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">
        导出
      </el-button>
    </div>

    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >
      <el-table-column label="用户名" width="200">
        <template slot-scope="scope">
          {{ scope.row.username }}
        </template>
      </el-table-column>
      <!-- <el-table-column label="密码" width="200" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.password }}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="姓名" width="200" align="center">
        <template slot-scope="scope">
          {{ scope.row.name }}
        </template>
      </el-table-column>
      <el-table-column label="性别" width="110" align="center">
        <template slot-scope="scope">
          {{ scope.row.gender == '1' ? '男' : '女' }}
        </template>
      </el-table-column>
      <el-table-column label="手机号" width="200" align="center">
        <template slot-scope="scope">
          {{ scope.row.phone }}
        </template>
      </el-table-column>
      <el-table-column label="头像" width="160" align="center">
        <template slot-scope="scope">
          <img class="img-circle" :src="scope.row.avatar">
        </template>
      </el-table-column>
      <el-table-column label="状态" width="170" align="center">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            active-color="#13ce66"
            inactive-color="#ff4949"
            @change="changeStatus(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="medium" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button size="medium" type="danger" @click="handleDelete(row,$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="page" :limit.sync="limit" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false" top="7vh">
      <el-form ref="dataForm" :rules="rules" :model="user" label-position="left" label-width="100px" style="width: 400px; margin-left:50px;">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="user.username" />
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="user.password" />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="user.name" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="user.gender" placeholder="请选择性别" clearable style="width: 300px" class="filter-item" @keyup.enter.native="handleFilter">
            <el-option v-for="item in genderOptions" :key="item.key" :label="item.label" :value="item.key" />
          </el-select>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="user.phone" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch
            v-model="user.status"
            active-color="#13ce66"
            inactive-color="#ff4949"
          />
        </el-form-item>
        <el-form-item label="角色" prop="roleIds">
          <el-select v-model="user.roleIds" placeholder="请选择角色" multiple clearable style="width: 300px" class="filter-item" @keyup.enter.native="handleFilter">
            <el-option v-for="item in roleOptions" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="头像">
          <pan-thumb :image="image" />
          <el-button type="primary" icon="el-icon-upload" @click="imagecropperShow=true">
            修改头像
          </el-button>
          <image-cropper
            v-show="imagecropperShow"
            :key="imagecropperKey"
            :width="300"
            :height="300"
            :url="BASE_API + '/minio/oss/upload/avatar'"
            filed="file"
            @close="close"
            @crop-upload-success="cropSuccess"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确定
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { getList, remove, save, update, getUser, getRoles, updateStatus } from '@/api/user'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import PanThumb from '@/components/PanThumb'
import ImageCropper from '@/components/ImageCropper'

export default {
  components: { Pagination, PanThumb, ImageCropper },
  directives: { waves },
  data() {
    return {
      list: null,
      listLoading: true,
      dialogLoading: true,
      total: 0,
      page: 1,
      limit: 10,
      userQuery: {
        username: '',
        name: '',
        gender: '',
        phone: '',
        status: ''
      },
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '添加'
      },
      user: {
        id: undefined,
        username: '',
        password: '',
        name: '',
        gender: '',
        phone: '',
        status: '',
        roleIds: [],
        avatar: ''
      },
      // 上传头像
      imagecropperShow: false,
      imagecropperKey: 0,
      BASE_API: process.env.VUE_APP_BASE_API,
      defaultImage: 'http://121.43.155.238:9000/dormitory/default.gif',
      image: '',
      dialogFormVisible: false,
      rules: {
        username: [{ required: true, message: '用户名不能为空', trigger: 'blur' }],
        password: [{ required: true, message: '密码不能为空', trigger: 'blur' },
          { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }],
        name: [{ required: true, message: '姓名不能为空', trigger: 'blur' }],
        gender: [{ required: true, message: '性别不能为空', trigger: 'blur' }],
        phone: [{ required: true, message: '手机号不能为空', trigger: 'blur' },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: '请输入正确的手机号码',
            trigger: 'blur'
          }],
        status: [{ required: true, message: '状态不能为空', trigger: 'blur' }],
        roleIds: [{ required: true, message: '角色不能为空', trigger: 'blur' }]
      },
      downloadLoading: false,
      genderOptions: [{ label: '男', key: 1 }, { label: '女', key: 0 }],
      statusOptions: [{ label: '正常', key: 1 }, { label: '停用', key: 0 }],
      roleOptions: []
    }
  },
  created() {
    this.getList()
    getRoles().then((response) => {
      this.roleOptions = response.data
    })
  },
  methods: {
    getList() {
      this.listLoading = true
      getList(this.page, this.limit, this.userQuery).then(response => {
        this.list = response.data.records
        this.total = response.data.total
        this.listLoading = false
      })
    },
    handleFilter() {
      this.page = 1
      this.getList()
    },
    // 头像上传成功
    cropSuccess(resData) {
      this.imagecropperShow = false
      this.imagecropperKey = this.imagecropperKey + 1
      this.image = resData
      this.user.avatar = resData
    },
    close() {
      this.imagecropperShow = false
    },
    changeStatus(row) {
      updateStatus(row).then(() => {
        this.$notify({
          title: 'Success',
          message: '状态修改成功',
          type: 'success',
          duration: 2000
        })
      })
    },
    handleCreate() {
      this.resetUser()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    resetUser() {
      this.user = {
        id: undefined,
        username: '',
        password: '',
        name: '',
        gender: '',
        phone: '',
        status: true,
        roleIds: [],
        avatar: this.defaultImage
      }
      this.image = this.defaultImage
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          save(this.user).then((response) => {
            this.dialogFormVisible = false
            this.list.unshift(response.data)
            this.$notify({
              title: 'Success',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      getUser(row.id).then((response) => {
        this.user = response.data
        // 如果数组为null,则无法push
        this.user.roleIds = []
        response.data.sysRoles.forEach(role => {
          this.user.roleIds.push(role.id)
        })
        this.image = response.data.avatar
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
      })
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          update(this.user).then((response) => {
            this.dialogFormVisible = false
            const index = this.list.findIndex(v => v.id === response.data.id)
            this.list.splice(index, 1, response.data)
            this.$notify({
              title: 'Success',
              message: '修改成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(row, index) {
      this.$notify({
        title: 'Success',
        message: '删除成功',
        type: 'success',
        duration: 2000
      })
      this.list.splice(index, 1)
      remove(row.id)
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['用户名', '密码', '姓名', '性别', '手机号', '头像', '状态']
        const filterVal = ['username', 'password', 'name', 'gender', 'phone', 'avatar', 'status']
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: '用户信息'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    }
  }
}
</script>
<style lang="scss" scoped>
.img-circle {
  border-radius: 50%;
  width: 60px;
  height: 60px;
}
</style>
